# coding=utf-8
# 全世界最帅的帅哥
# 测试链接：https://leetcode.cn/problems/add-two-numbers/
# 提交的时候把class ListNode给注释掉 copy class Solution就行
from typing import Optional


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:

        ans, carry, cur = None, 0, None
        while l1 or l2 or carry:

            sum_ = (int(l1.val) if l1 else 0) + (int(l2.val) if l2 else 0) + carry
            value = sum_ % 10
            carry = sum_ // 10

            if not ans:
                ans = ListNode(value)
                cur = ans
            else:
                node = ListNode(value)
                cur.next = node
                cur = cur.next

            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return ans


